import { onMounted, reactive, ref, toRaw } from "vue";
import { getVideoList } from "@/api/video";

import type { PaginationProps } from "@pureadmin/table";
import { useAvStoreHook } from "@/store/modules/av";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";

export function useMovie() {
  const route = useRoute();
  const router = useRouter();
  const { avListStore } = useAvStoreHook();

  const dataList = ref([]);
  const loading = ref(true);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 40,
    pageSizes: [30, 40, 75, 100],
    currentPage: 1,
    background: true
  });

  const form = reactive({
    id: "",
    title: "",
    code: "",
    status: "",
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize
  });

  const onSearch = async () => {
    try {
      const { data } = await getVideoList(toRaw(form));
      console.log("data:", data.list);
      dataList.value = data.list;
      avListStore.dataList = dataList.value; // pinia存值
      pagination.total = data.total;
      pagination.pageSize = data.pageSize;
      pagination.currentPage = data.currentPage;
      console.log("dataList hooks:", dataList);
      const dataSingle = data.list;
      console.log("dataSingle:", dataSingle[0]);
      dataList.value = dataSingle;
      console.log("dataList.value:", dataList.value);
    } catch (error) {
      console.log(error);
      ElMessage({
        message: error,
        type: "error"
      });
    }
  };

  onMounted(() => {
    onSearch();
  });

  const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  };
  const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    form.currentPage = val;
    onSearch();
  };

  return {
    pagination,
    handleSizeChange,
    handleCurrentChange,
    loading,
    form,
    avListStore,
    dataList,
    onSearch,
    route,
    router
  };
}
